<template>
  <div class="left-top-container">
    <!-- 时间切换按钮 -->
    <!-- <div class="time-switch">
      <div 
        class="switch-btn" 
        :class="{ active: activeTimeType === 'year' }" 
        @click="switchTimeType('year')"
      >
        年
      </div>
      <div 
        class="switch-btn" 
        :class="{ active: activeTimeType === 'month' }" 
        @click="switchTimeType('month')"
      >
        月
      </div>
      <div 
        class="switch-btn" 
        :class="{ active: activeTimeType === 'day' }" 
        @click="switchTimeType('day')"
      >
        日
      </div>
    </div> -->
    
    <!-- 图表区域 -->
    <div class="chart-container">
      <v-chart class="chart" :option="chartOption" v-if="JSON.stringify(chartOption) !== '{}'" style="height: 100%;"/>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { dateInfo } from '@/utils/dateInfo'
import { graphic } from 'echarts/core'
import { GreenPowerApi, type PowerCurveData } from '@/api/green-power'

const activeTimeType = ref('day')
const chartOption = ref({})
const loading = ref(false)
const powerData = ref<PowerCurveData[]>([])
const totalPower = ref(0)
const avgEfficiency = ref(0)

// 获取功率曲线数据
const fetchPowerCurveData = async () => {
  try {
    loading.value = true
    const response = await GreenPowerApi.getPowerCurve()
    if (response.success) {
      powerData.value = response.data.list
      totalPower.value = response.data.totalPower
      avgEfficiency.value = response.data.avgEfficiency
      updateChart()
    }
  } catch (error) {
    console.error('获取功率曲线数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 模拟数据（备用）
const mockData = reactive({
  year: {
    xData: ['2019', '2020', '2021', '2022', '2023', '2024'],
    yData: [1200, 1800, 2400, 3200, 4100, 4800]
  },
  month: {
    xData: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    yData: [320, 280, 450, 520, 680, 720, 850, 900, 750, 650, 480, 380]
  },
  day: {
    xData: ['00时', '01时', '02时', '03时', '04时', '05时', '06时', '07时', '08时', '09时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时'],
    yData: [0, 0, 0, 0, 0, 58, 69, 75, 82, 84, 88, 90, 100, 94, 90, 88, 72, 63, 60, 0, 0, 0, 0, 0]
  }
})

const switchTimeType = (type: string) => {
  activeTimeType.value = type
  updateChart()
}

const updateChart = () => {
  // 优先使用接口数据，如果没有则使用模拟数据
  let xData: string[] = []
  let yData: number[] = []
  
  if (powerData.value.length > 0) {
    // 使用接口数据
    xData = powerData.value.map(item => item.time)
    yData = powerData.value.map(item => item.power)
  } else {
    // 使用模拟数据
    const currentData = mockData[activeTimeType.value as keyof typeof mockData]
    xData = currentData.xData
    yData = currentData.yData
  }
  
  chartOption.value = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'rgba(124, 189, 207, 0.8)',
      textStyle: {
        color: '#ffffff'
      },
      formatter: function(params: any) {
        return `${params[0].name}<br/>${params[0].marker}瞬时功率: ${params[0].value}kW`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData,
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: '#7EB7FD',
        fontSize: 12
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(31, 99, 163, 0.2)'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '瞬时功率(kW)',
      nameTextStyle: {
        color: '#7EB7FD',
        fontSize: 12
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: '#7EB7FD',
        fontSize: 12
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(31, 99, 163, 0.2)'
        }
      }
    },
    series: [
      {
        name: '瞬时功率',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        data: yData,
        lineStyle: {
          color: '#00d4ff',
          width: 3
        },
        itemStyle: {
          color: '#00d4ff',
          shadowColor: '#00d4ff',
          shadowBlur: 10
        },
        areaStyle: {
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(0, 212, 255, 0.6)'
            },
            {
              offset: 1,
              color: 'rgba(0, 212, 255, 0.1)'
            }
          ])
        }
      }
    ]
  }
}

const timer = ref()
onMounted(async () => {
  await nextTick(() => {
    // 获取接口数据
    // fetchPowerCurveData()
    
    // 备用：根据今天的日期，在dateInfo 中找到对应日期的数据
    const today = new Date().getMonth() + 1 + '月' + new Date().getDate() + '日'
    const todayData = dateInfo.find(item => item.date === today)
    console.log('todayData', todayData)

    // 如果接口数据获取失败，使用模拟数据
    timer.value = setTimeout(() => {
      if (powerData.value.length === 0) {
        updateChart()
      }
      clearTimeout(timer.value)
    }, 2000)
  })
})
</script>

<style lang="less" scoped>
.left-top-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;
  box-sizing: border-box;
}

.time-switch {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
  background: rgba(0, 30, 60, 0.6);
  border-radius: 20px;
  padding: 4px;
  
  .switch-btn {
    padding: 6px 16px;
    margin: 0 2px;
    border-radius: 16px;
    color: #7EB7FD;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      background: rgba(0, 212, 255, 0.2);
      color: #00d4ff;
    }
    
    &.active {
      background: linear-gradient(90deg, #00d4ff 0%, #0099cc 100%);
      color: #ffffff;
      box-shadow: 0 2px 8px rgba(0, 212, 255, 0.4);
    }
  }
}

.chart-container {
  flex: 1;
  height: 100%;
  .chart {
    width: 100%;
    height: 100%;
    :deep(.vue-echarts-inner){
      div:nth-child(1){
        height: 100% !important;
      }
    } 
  }
}
</style>